//
//  ZCMainViewController.m
//  VoiceMusic
//
//  Created by dllo on 15/10/15.
//  Copyright © 2015年 zhangdeyu. All rights reserved.
//

#import "ZCMainViewController.h"
#import <RESideMenu.h>


#import "ZCMVViewController.h"

#import "ZCRecommendViewController.h"
#import <Masonry.h>
#import <UIImageView+WebCache.h>
#import "ZCAFNetWork.h"
#import "ZCMainTableViewCell.h"
#import "ZCCollectionTableViewCell.h"
#import "ZCMainModel.h"
#import "ZCBaseScrollerView.h"

#import "ZCChartsViewController.h"
#import "ZCMusicListViewController.h"
#import "ZCMVViewController.h"
#import "ZCSingerViewController.h"

#import <AVFoundation/AVFoundation.h>
#import "ZCPlayMusicTool.h"
#import "ZCDetaileListViewController.h"

#import "ZCDeListViewController.h"
#import "ZCSaveViewController.h"
#import "ZCLoadViewController.h"
#import "ZCAboutUsViewController.h"


@interface ZCMainViewController ()

@end
@interface ZCMainViewController ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) ZCBaseScrollerView *scriollView;
@property (nonatomic, strong) UIView * heatView;
@property (nonatomic, strong) UIImageView *buttonView;
@property (nonatomic, strong) UILabel *labelView;
@property (nonatomic, strong) NSMutableArray *listenArr;
@property (nonatomic, strong) NSMutableArray *menuArr;
@property (nonatomic, strong) NSMutableArray *playImageArr;
@property (nonatomic, strong) NSMutableArray *functionArr;
@property (nonatomic, strong) NSTimer *timer;

@property (nonatomic, strong) AVPlayer *player;

//是否是我点击的歌曲(如果不是就是刚启动就可以播放的歌曲的本地连接)
@property (nonatomic, assign) BOOL isSelect;

//用于判断重复点击歌曲,每次保存点击的歌曲的url
@property (nonatomic, copy) NSString *lastStr;

@end

@implementation ZCMainViewController


- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if(self){
        self.listenArr = [NSMutableArray array];
        self.menuArr = [NSMutableArray array];
        self.playImageArr = [NSMutableArray array];
        self.functionArr = [NSMutableArray array];
    }
    return self;
}

- (void)creatData{
    [ZCAFNetWork getUrl:@"http://api.dongting.com/frontpage/frontpage?v=v8.1.0.2015071519&f=f168&s=s200&version=0" body:nil result:ZCJSON headerFile:nil success:^(id result) {
        NSDictionary *dic = result;
        NSArray *arr = dic[@"data"];
        if(arr.count != 0){
            for (NSInteger i = 0; i<4; i++) {
                switch (i) {
                    case 0:{
                        NSDictionary *dicData = arr[0];
                        self.playImageArr = [ZCMainModel baseModelByArr:dicData[@"data"]];

                        [self.scriollView playImage:self.scriollView imageArr:self.playImageArr];
                        
                        /**
                         *  轮播图添加手势
                         */
                        for (id view in [self.scriollView subviews]) {
                            if([view isKindOfClass:[UIImageView class]]){
                                UIImageView *img = (UIImageView *)view;
                                img.userInteractionEnabled = YES;
                                UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(fingerIncident:)];
                                tap.numberOfTapsRequired = 1;
                                tap.numberOfTouchesRequired = 1;
                                [img addGestureRecognizer:tap];
                            }
                        }

                        
                        [self addTimer];
                        break;
                    }
                    case 1:{
                        NSDictionary *dicData = arr[1];
                        self.functionArr = [ZCMainModel baseModelByArr:dicData[@"data"]];
                        for (NSInteger i = 0; i< 4; i++) {
                            ZCMainModel *model = self.functionArr[i];
                            NSString *url = [model.picUrl substringToIndex:90];
                            self.buttonView = (UIImageView *)[self.view viewWithTag:1001+i];
                            [self.buttonView sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:@"iconfont-bofang"]];
                            self.labelView = (UILabel *)[self.view viewWithTag:2001 + i];
                            if(i == 2){
                                self.labelView.text = @"MV";
                            }else{
                                self.labelView.text = model.name;
                            }
                            
                        }
                        break;
                    }
                    case 2:{
                        NSDictionary *dicData = arr[2];
                        NSArray *detailsArr = dicData[@"data"];
                        NSDictionary *detailsDic = detailsArr[0];
                        self.listenArr = [ZCMainModel baseModelByArr:detailsDic[@"songs"]];
                        break;
                    }
                    case 3:{
                        NSDictionary *dicData = arr[3];
                        self.menuArr = [ZCMainModel baseModelByArr:dicData[@"data"]];
                         break;
                    }
                    default:
                        break;
                }
            }
        }
    [self.tableView reloadData];
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
    }];
    
}
/**
 *  手势的点击方法
 */
-(void)fingerIncident:(UITapGestureRecognizer *)tap{
    
    ZCDeListViewController *scoDetails = [[ZCDeListViewController alloc] init];
    
    NSInteger tapNum = self.scriollView.contentOffset.x/WIDTH;
    if(tapNum == 0){
        ZCMainModel *model = self.playImageArr[self.playImageArr.count-1];
        
        if([model.action[@"type"] isEqualToString:@"1"])return;
        scoDetails.myId = model.action[@"value"];
        
    }else if(tapNum == self.playImageArr.count+1){
        
        ZCMainModel *model = self.playImageArr[0];
        if([model.action[@"type"] isEqualToString:@"1"])return;
        scoDetails.myId= model.action[@"value"];
    }else{
        ZCMainModel *model=self.playImageArr[tapNum-1];
        NSString *str =[NSString stringWithFormat:@"%@",model.action[@"type"]];
        if([str isEqualToString:@"1"])return;

        scoDetails.myId = model.action[@"value"];
    }
    
    [self.navigationController pushViewController:scoDetails animated:YES];

}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    if(self.scriollView.contentOffset.x == (self.playImageArr.count + 1) * WIDTH){
        
        self.scriollView.contentOffset = CGPointMake(WIDTH, 0);
    
    }else if ( self.scriollView.contentOffset.x == 0){
    
        self.scriollView.contentOffset = CGPointMake(self.playImageArr.count * WIDTH, 0);
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    [self addTimer];
    if(self.scriollView.contentOffset.x == (1+self.playImageArr.count)*WIDTH){
        self.scriollView.contentOffset = CGPointMake(WIDTH, 0);
        
    }else if(self.scriollView.contentOffset.x == 0){
        self.scriollView.contentOffset = CGPointMake(self.playImageArr.count*WIDTH, 0);
    }
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self removeTimer];
}



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"side"] style: UIBarButtonItemStyleDone target:self action:@selector(presentRightMenuViewController:)];
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"750365_105833058_2"]];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"推荐" style:UIBarButtonItemStyleDone target:self action:@selector(recommend:)];
    
    
    //控制模态跳转
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushView:) name:@"nava" object:nil];
    
    [self creatView];
    
    [self creatData];
 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(blue:) name:@"collection" object:nil];
   
}
// 推荐按钮
- (void)recommend:(UIBarButtonItem *)button
{
    ZCRecommendViewController *recommendvc = [[ZCRecommendViewController alloc] init];
    [self.navigationController pushViewController:recommendvc animated:YES];
}
//抽屉跳转
-(void)pushView:(NSNotification *)not{
    if([not.userInfo[@"type"] isEqualToString:@"1"]){
        ZCSaveViewController *save = [[ZCSaveViewController alloc] init];
        [self.navigationController pushViewController:save animated:YES];
    }else if ([not.userInfo[@"type"] isEqualToString:@"2"]){
        ZCLoadViewController *load = [[ZCLoadViewController alloc] init];
        [self.navigationController pushViewController:load animated:YES];
        
    }else if([not.userInfo[@"type"] isEqualToString:@"3"]){
         ZCAboutUsViewController *aboutUsVC = [[ZCAboutUsViewController alloc] init];
         [self.navigationController pushViewController:aboutUsVC animated:YES];
    }
    
    

}
//歌单界面跳转
-(void)blue:(NSNotification *)not{
    
    ZCDeListViewController *hot = [[ZCDeListViewController alloc] init];
    hot.myId = not.userInfo[@"value"];
    [self.navigationController pushViewController:hot animated:YES];
    
}

- (void)creatView{
    self.tableView = [[UITableView alloc] init];
    //self.tableView.rowHeight = 100;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        //make.edges.equalTo(self.view);
        make.top.left.right.equalTo(self.view);
        make.height.equalTo(@(HEIGHT- 64 - 49));
    }];
    
    self.heatView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT / 4 +100)];
    //self.heatView.backgroundColor = [UIColor redColor];
    self.tableView.tableHeaderView = self.heatView;
    
    self.scriollView = [[ZCBaseScrollerView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT/4+30)];
    self.scriollView.pagingEnabled=YES;
    self.scriollView.bounces=NO;
    self.scriollView.delegate = self;
    self.scriollView.showsHorizontalScrollIndicator=NO;
    self.scriollView.showsVerticalScrollIndicator=NO;
    self.scriollView.contentOffset = CGPointMake(WIDTH, 0);
    [self.heatView addSubview:self.scriollView];
    
    for (NSInteger i = 0; i < 4; i++) {
        self.buttonView = [[UIImageView alloc] initWithFrame:CGRectMake(20 + i * WIDTH / 4 , HEIGHT/3.8 + 30, WIDTH / 6 - 10, 25)];
        self.buttonView.tag = 1001 + i;
        self.buttonView.contentMode = UIViewContentModeScaleAspectFit;
        self.labelView = [[UILabel alloc] initWithFrame:CGRectMake( i * WIDTH / 4, HEIGHT/4 + 65, WIDTH / 4, 30)];
        self.labelView.textAlignment = NSTextAlignmentCenter;
        [self.heatView addSubview:self.buttonView];
        [self.heatView addSubview:self.labelView];
        self.labelView.tag = 2001 + i;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapp:)];
        tap.numberOfTapsRequired = 1;
        tap.numberOfTouchesRequired = 1;
        UITapGestureRecognizer *tapL = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapp:)];
        tapL.numberOfTapsRequired = 1;
        tapL.numberOfTouchesRequired = 1;

        self.buttonView.userInteractionEnabled = YES;
        
        self.labelView.userInteractionEnabled = YES;
        [self.labelView addGestureRecognizer:tapL];
        
        [self.buttonView addGestureRecognizer:tap];
    }
    
}
//分类(4个)点击方法
-(void)tapp:(UITapGestureRecognizer *)tap{
    
    switch (tap.view.tag) {
        case 1001:{
            ZCChartsViewController *chart = [[ZCChartsViewController alloc] init];
            [self.navigationController pushViewController:chart animated:YES];
            break;
        }
        case 2001:{
            ZCChartsViewController *chart = [[ZCChartsViewController alloc] init];
            [self.navigationController pushViewController:chart animated:YES];
            break;
        }
         case 1002:
        {
            ZCMusicListViewController *musicList = [[ZCMusicListViewController alloc] init];
            [self.navigationController pushViewController:musicList animated:YES];
            break;
        }
        case 2002:
        {
            ZCMusicListViewController *musicList = [[ZCMusicListViewController alloc] init];
            [self.navigationController pushViewController:musicList animated:YES];
            break;

        }
        case 1003:
        {
            ZCMVViewController *MV = [[ZCMVViewController alloc] init];
            [self.navigationController pushViewController:MV animated:YES];
            break;
        }
        case 2003:
        {
            ZCMVViewController *MV = [[ZCMVViewController alloc] init];
            [self.navigationController pushViewController:MV animated:YES];
            break;
        }
        case 1004:
        {
            ZCSingerViewController *singer = [[ZCSingerViewController alloc] init];
            [self.navigationController pushViewController:singer animated:YES];
            break;
        }
        case 2004:
        {
            ZCSingerViewController *singer = [[ZCSingerViewController alloc] init];
            [self.navigationController pushViewController:singer animated:YES];
            break;
        }

        default:
            break;
    }
}

- (void)changePic{
    [self.scriollView setContentOffset:CGPointMake(self.scriollView.contentOffset.x + WIDTH, 0) animated:YES];
    if(self.scriollView.contentOffset.x == (self.playImageArr.count+1) * WIDTH){
        self.scriollView.contentOffset = CGPointMake(WIDTH, 0);
    }
}


//添加
-(void)addTimer
{
    //自动
    NSTimer *time = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(changePic) userInfo:nil repeats:YES];
    //NSRunLoop持有NSTimer ,保证安全
    [[NSRunLoop currentRunLoop] addTimer:time forMode:NSRunLoopCommonModes];
    self.timer = time;
}

//在手动滑动的时候,移除掉Timer
-(void)removeTimer
{
    //将Timer释放,(release操作)
    [self.timer invalidate];
    //置空
    self.timer = nil;
}



- (NSInteger )tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section == 0){
        return self.listenArr.count;
    }else{
        return 1;
    }
   
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0){
        static NSString *re = @"re";
        ZCMainTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:re];
        if (!cell) {
            cell = [[ZCMainTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:re];
        }
        ZCMainModel *main = self.listenArr[indexPath.row];
        cell.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:main.picUrl] placeholderImage:[UIImage imageNamed:@"3187"]];
        cell.titleLabel.text = main.name;
        cell.titleLabel.numberOfLines = 0;
        cell.detailLabel.text = main.singerName;
        cell.iconImageView.image = [UIImage imageNamed:@"iconfont-bofang"];
        cell.foImageView.image = [UIImage imageNamed:@"like"];
        cell.firstLabel.text = [NSString stringWithFormat:@"%@",main.favorites];
        return cell;
    }
    else{
        static NSString *rec = @"rec";
        
        ZCCollectionTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:rec];
        if (!cell) {
            cell = [[ZCCollectionTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:rec];
        }
        cell.backgroundColor = [UIColor clearColor];
        cell.dataCellArr = self.menuArr;
        [cell.collectionView reloadData];
        return cell;
    }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    return @"111";
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIButton *bu = [UIButton buttonWithType:UIButtonTypeCustom];
    [bu setTitle:@"热门歌曲" forState:UIControlStateNormal];
    [bu setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    UIView *vie = [[UIView alloc] init];
    vie.backgroundColor = [UIColor colorWithRed:1.000 green:0.828 blue:0.584 alpha:1.000];
    [vie addSubview:bu];
    
    [bu mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.bottom.equalTo(vie);
        make.width.equalTo(@100);
    }];
    if(section == 0){
        [bu setTitle:@"大家在听" forState:UIControlStateNormal];
    }else{
        [bu setTitle:@"热门歌曲" forState:UIControlStateNormal];
      
    }
    return vie;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0){
        return 100;
    }else{
        return 230;
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //传值
    if(indexPath.section == 0){
        ZCMainModel *model = self.listenArr[indexPath.row];
        
        //判断歌曲是否重复点击
        if([self.lastStr isEqualToString:model.auditionList[0][@"url"]])return;
        
        self.lastStr = model.auditionList[0][@"url"];
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:model.name,@"name",model.singerName,@"nameSinge",model.picUrl,@"heat",model.auditionList[0][@"url"],@"url",nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"play" object:self userInfo:dic];
        //播放音乐
        [ZCPlayMusicTool getPlay:model.auditionList[0][@"url"]];
        [ZCPlayMusicTool sharePlay].urlMusic = model.auditionList[0][@"url"];
        //发送监听列表的属性
        NSDictionary *arrDic = [NSDictionary dictionaryWithObjectsAndKeys:self.listenArr,@"arr", nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"arr" object:nil userInfo:arrDic];
        
        [ZCPlayMusicTool sharePlay].pross = @"0";
    }
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
